package com.qiyou.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qiyou.dao.IBlogDao;
import com.qiyou.dao.factory.DaoFactory;
import com.qiyou.entity.Blog;
import com.qiyou.entity.User;

/**
 * 用户博客添加
 */
@WebServlet(name = "AddBlog", urlPatterns = { "/AddBlog" })
public class AddBlogServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		IBlogDao dao = DaoFactory.getBlogDao();
		
		Blog blog = new Blog();
		
		User user = (User)request.getSession().getAttribute("user");
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		
		if (null != user) {
			blog.setBlogContent(content);
			blog.setBlogTitle(title);
			blog.setUserID(user.getID());
			
			try {
				if (dao.doCreate(blog)) {
					String userId = user.getID();
					request.getRequestDispatcher("BlogList?userId="+userId).forward(request, response);
				}
			} catch (Exception e) {
				e.printStackTrace();
				response.getWriter().print("<script type='text/javascript'>alert('保存博客时出错');history.go(-1);</script>");
			}
		}else {
			response.getWriter().print("<script type='text/javascript'>alert('您请求的参数有误或者没登陆');history.go(-1);</script>");
		}
	}

}
